package thinkinjava4.ch22_gui;

import thinkinjava4.util.TaskItem;
import thinkinjava4.util.TaskManager;

import javax.swing.*;
import java.awt.*;
import java.util.concurrent.Callable;

class CallableTask extends Task implements Callable<String> {
    @Override
    public String call() throws Exception {
        run();
        return "Return value of " + this;
    }
}

public class InterruptableLongRunningCallable extends JFrame {
    private JButton b1 = new JButton("Start Long Running Task");
    private JButton b2 = new JButton("End Long Running Task");
    private JButton b3 = new JButton("Get results");
    private TaskManager<String, CallableTask> manager = new TaskManager<>();

    public InterruptableLongRunningCallable() {
        b1.addActionListener(event -> {
            CallableTask task = new CallableTask();
            manager.add(task);
            System.out.println(task + " added to the queue");
        });
        b2.addActionListener(event -> {
            for (String result : manager.purge()) System.out.println(result);
        });
        b3.addActionListener(event -> {
//            for (TaskItem<String, CallableTask> tt : manager) tt.task.id();
            for (String result : manager.getResults()) System.out.println(result);
        });
        setLayout(new FlowLayout());
        add(b1);
        add(b2);
        add(b3);
    }

    public static void main(String[] args) {
        SwingConsole.run(new InterruptableLongRunningCallable(), 300, 150);
    }
}
